/***************************************************
> Copyright (C) 2024 ==KINGYI== All rights reserved.
> File Name: server.c
> Author:cjy
> Mail: 
> Created Time: 2024年08月13日 星期2 16时19分12秒
***************************************************/
//基于基于udp协议开发一个简易时间服务器。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "cJSON.h"
struct data
{
	int type;
	char count[10];
	float num1;
	float num2;
};

struct number
{
	float sum;
};


int main(int argc,const char* argv[])
{
	int sock = 0;
	int ret = 0;
	char buf[1024] = {0};
	char *dest = NULL;

	struct sockaddr_in addr;
        memset(&addr,0,sizeof(addr));

	sock = socket(AF_INET,SOCK_DGRAM,0);
	if(sock == -1)
	{
		perror("sock");
		exit(-1);
	}

	addr.sin_family = AF_INET;
        addr.sin_port = htons(6666);
        addr.sin_addr.s_addr = inet_addr("192.168.198.128");

	ret = bind(sock,(struct sockaddr *)&addr,sizeof(struct sockaddr));
	if(ret == -1)
	{
		perror("bind");
		exit(-1);
	}

	struct sockaddr_in cliaddr;
	memset(&cliaddr,0,sizeof(cliaddr));

	int len = sizeof(struct sockaddr);

while(1){
	ret = recvfrom(sock,buf,1024,0,(struct sockaddr *)&cliaddr,&len);
		if(ret == -1)
		{
			perror("recvfrom");
			exit(-1);
		}
	puts(buf);
	cJSON *json = NULL;
	
	struct data dat;
	memset(&dat,0,sizeof(dat));

	struct number num;
	memset(&num,0,sizeof(num));
	
	json = cJSON_Parse(buf);

	cJSON *node = NULL;

	node = cJSON_GetObjectItem(json,"type");
	if(node == NULL)
	{
		printf("can't find\n");
		exit(-1);
	}
	if(node->type == cJSON_Number)
	{
		dat.type = node->valueint;
	}
	


	node = cJSON_GetObjectItem(json,"count");
	if(node == NULL)
	{
		printf("can't find\n");
		exit(-1);
	}
	if(node->type == cJSON_String)
	{
		strcpy(dat.count,node->valuestring);
	}


	node = cJSON_GetObjectItem(json,"num1");
	if(node == NULL)
	{
		printf("can't find\n");
		exit(-1);
	}
	if(node->type == cJSON_Number)
	{
		dat.num1 = node->valuedouble;
	}



	node = cJSON_GetObjectItem(json,"num2");
	if(node == NULL)
	{
		printf("can't find\n");
		exit(-1);
	}
	if(node->type == cJSON_Number)
	{
		dat.num2 = node->valuedouble;
	}
	

		if(dat.type == 1)
		{
		num.sum = dat.num1 + dat.num2;
		printf("%f\n",num.sum);
		}

		else if(dat.type == 2)
		{
		num.sum = dat.num1 - dat.num2;
		printf("%f\n",num.sum);
		}

		else if(dat.type == 3)
		{
		num.sum = dat.num1 * dat.num2;
		printf("%f\n",num.sum);
		}
		else if(dat.type == 4)
		{
		num.sum = dat.num1 / dat.num2;
		printf("%f\n",num.sum);
		}

		
		json = cJSON_CreateObject();

		cJSON_AddItemToObject(json,"sum",cJSON_CreateNumber(num.sum));	
	
		dest = cJSON_Print(json);
	
    		ret = sendto(sock,dest,strlen(dest),0,(struct sockaddr *)&cliaddr,sizeof(struct sockaddr));
		if(ret == -1)
		{
			perror("sendto");
		}
	
	cJSON_Delete(json);
}


	

	close(sock);


    return 0;
}
